package com.yanqu.road.server.manager.activity.celebration;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.celebration.CelebrationActivityConfig;
import com.yanqu.road.entity.activity.celebration.CelebrationCrossProgress;
import com.yanqu.road.entity.activity.celebration.CelebrationScoreConfig;
import com.yanqu.road.entity.config.goods.GoodsInfo;
import com.yanqu.road.entity.log.LogCelebrationFestiveCrossChange;
import com.yanqu.road.logic.bussiness.activity.CelebrationBusiness;
import com.yanqu.road.pb.celebration.CelebrationProto;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.activity.ActivityMgr;
import com.yanqu.road.server.manager.config.GoodsMgr;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.utils.date.DateHelper;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description 周年庆活动
 * @Author cwq
 * @Data 2022/4/24 15:57
 */
public class CelebrationActivity {

    private int activityId;

    /**
     * 修复进度
     */
    private Map<Integer, CelebrationCrossProgress> buildingProgressMap = new ConcurrentHashMap<>();

    public CelebrationActivity(int activityId) {
        this.activityId = activityId;
        initActivityInfo();
    }

    public void initActivityInfo() {
        buildingProgressMap = CelebrationBusiness.getCelebrationProgressMap(activityId);
    }

    public boolean save() {
        for (CelebrationCrossProgress item : buildingProgressMap.values()) {
            if (item.isInsertOption()) {
                CelebrationBusiness.addCelebrationProgress(item);
            } else if (item.isUpdateOption()) {
                CelebrationBusiness.updateCelebrationProgress(item);
            }
        }
        return true;
    }

    /**
     * 进入周年庆
     *
     * @return
     */
    public CelebrationProto.CelebrationGetProgressRespMsg.Builder enter() {
        CelebrationProto.CelebrationGetProgressRespMsg.Builder builder = CelebrationProto.CelebrationGetProgressRespMsg.newBuilder();
        for (CelebrationCrossProgress item : buildingProgressMap.values()) {
            CelebrationProto.CelebrationProgress.Builder progress = CelebrationProto.CelebrationProgress.newBuilder();
            progress.setId(item.getId());
            progress.setScore(item.getScore());
            builder.addProgressList(progress);
        }
        builder.setRet(0);
        return builder;
    }

    /**
     * 修复
     *
     * @param builder
     * @return
     */
    public void useProp(CelebrationProto.CelebrationUsePropCrossToGameMsg.Builder builder) {
        // 随机修复建筑
        List<Integer> canRandomList = new ArrayList<>();
        HashMap<Integer, Long> addScoreMap = new HashMap<>();
        CelebrationActivityConfig activityConfig = CelebrationConfigMgr.getConfigMap().get(activityId);
        GoodsInfo goodsInfo = GoodsMgr.getGoodsInfo(builder.getPropId());
        synchronized (buildingProgressMap) {
            long oldValue = getCelebrationLv();
            for (CelebrationScoreConfig item : activityConfig.getScoreConfigList()) {
                CelebrationCrossProgress progress = buildingProgressMap.get(item.getId());
                if (progress != null && item.timesList.size() > 0 && item.timesList.get(item.timesList.size() - 1) <= progress.getScore()) {
                    continue;
                }
                canRandomList.add(item.getId());
            }
            if (canRandomList.size() > 0) {
                Random random = new Random();
                for (int i = 0; i < builder.getNum(); i++) {
                    int index = random.nextInt(canRandomList.size());
                    int randomId = canRandomList.get(index);
                    CelebrationCrossProgress celebrationProgress = buildingProgressMap.get(randomId);
                    if (celebrationProgress == null) {
                        celebrationProgress = new CelebrationCrossProgress();
                        celebrationProgress.setInsertOption();
                        celebrationProgress.setActivityId(activityId);
                        celebrationProgress.setId(randomId);
                        buildingProgressMap.put(randomId, celebrationProgress);
                    }
                    List<Long> timesList = activityConfig.getScoreConfigMap().get(randomId).timesList;
                    long maxScore = timesList.get(timesList.size() - 1);
                    long needScore = maxScore - celebrationProgress.getScore();
                    long addScore = Math.min(needScore, goodsInfo.getParamList().get(0).intValue());
                    // 加进度
                    celebrationProgress.setScore(celebrationProgress.getScore() + addScore);
                    addScoreMap.put(randomId, addScoreMap.getOrDefault(randomId, 0L) + addScore);
                    if (celebrationProgress.getScore() >= maxScore) {
                        canRandomList.remove(index);
                        if (canRandomList.size() <= 0) {
                            break;
                        }
                    }

                }
            }
            for (Map.Entry<Integer, Long> entry : addScoreMap.entrySet()) {
                CelebrationProto.CelebrationProgress.Builder progressBuilder = CelebrationProto.CelebrationProgress.newBuilder();
                progressBuilder.setId(entry.getKey());
                progressBuilder.setScore(entry.getValue());
                progressBuilder.setCurValue(buildingProgressMap.get(entry.getKey()).getScore());
                builder.addAddProgress(progressBuilder);
            }
            builder.setLogTime(DateHelper.getCurrentTime());
            builder.setCurLv(getCelebrationLv());
            // 同步喜庆值
            synFestiveValue(oldValue, getCelebrationLv());
            builder.setRet(0);
        }
    }


    /**
     * 获取当前庆典建筑总等级
     *
     * @return
     */
    public int getCelebrationLv() {
        CelebrationActivityConfig activityConfig = CelebrationConfigMgr.getConfigMap().get(activityId);
        int totalLv = 0;
        for (CelebrationCrossProgress item : buildingProgressMap.values()) {
            CelebrationScoreConfig config = activityConfig.getScoreConfigMap().get(item.getId());
            if (config != null) {
                for (Long times : config.timesList) {
                    if (item.getScore() >= times) {
                        totalLv++;
                    } else {
                        break;
                    }
                }
            }
        }
        return totalLv;
    }

    /**
     * 同步喜庆值 夸了领奖档次同步喜庆值
     */
    public void synFestiveValue(long oldValue, long newValue) {
        if (oldValue >= newValue) {
            return;
        }
        // 加日志
        StringBuilder info = new StringBuilder();
        CelebrationActivityConfig activityConfig = CelebrationConfigMgr.getConfigMap().get(activityId);
        for (CelebrationCrossProgress item : buildingProgressMap.values()) {
            // 当前阶段
            int lv = 0;
            CelebrationScoreConfig config = activityConfig.getScoreConfigMap().get(item.getId());
            if (config != null) {
                for (long times : config.timesList) {
                    if (item.getScore() >= times) {
                        lv++;
                    } else {
                        break;
                    }
                }
            }
            if (lv != 0) {
                if (info.length() > 0) {
                    info.append(";");
                }
                info.append(item.getId()).append("|").append(lv);
            }
        }
        CelebrationLogMgr.addLogCelebrationFestiveChange(new LogCelebrationFestiveCrossChange(activityId, newValue - oldValue, newValue, info.toString(), DateHelper.getCurrentSecond()));
        synBuildLv(0, 0);
    }

    /**
     * 同步周年庆等级
     *
     * @param targetServerId 目标区服 0表示同步所有活动区服
     * @param playerId
     */
    public void synBuildLv(long targetServerId, long playerId) {
        CelebrationProto.CelebrationSynLvCrossToGameMsg.Builder builder = CelebrationProto.CelebrationSynLvCrossToGameMsg.newBuilder();
        builder.setCurLv(getCelebrationLv());
        if (targetServerId == 0) {
            ActivityInfo activityInfo = ActivityMgr.getActivityInfo(activityId);
            if (activityInfo != null) {
                activityInfo.getServerIdList().forEach(serverId -> {
                    MessageHelper.sendPacket(serverId, 0, YanQuMessageUtils.buildMessage(GameProtocol.S_CELEBRATION_SYN_LV_CROSS_TO_GAME, builder));
                });
            }
        } else {
            MessageHelper.sendPacket(targetServerId, playerId, YanQuMessageUtils.buildMessage(GameProtocol.S_CELEBRATION_SYN_LV_CROSS_TO_GAME, builder));
        }
    }


}
